/**
 * BaseController.java
 */
package org.yate.oa.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.alibaba.fastjson.JSONObject;

/**
 * @author Yate
 * @date 2013年9月21日
 * @description 基于Servlet3.x实现的基础Controller
 * @version 1.0
 */
public abstract class BaseServletController extends HttpServlet {
	protected final Logger log = LoggerFactory.getLogger(this.getClass());

	protected ServletContext context;
	protected ApplicationContext springCtx;

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig)
	 */
	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		if (this.context == null) {
			this.context = config.getServletContext();
			this.springCtx = WebApplicationContextUtils
					.getWebApplicationContext(this.context);
		}
	}
	
	@Override
    public final void service(ServletRequest req, ServletResponse res) throws IOException {
        try {
            super.service(req, res);
        } catch (Exception e) {
            PrintWriter out = res.getWriter();
            JSONObject json = new JSONObject();
            json.put("status", "500");
            json.put("data", e.toString());
            out.println(json);
            out.flush();
            out.close();
        }
    }
}
